package com.yyplatform.frontend.infra.web.resolver;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.yyplatform.frontend.infra.web.jwt.CurrentUserHolder;

import jakarta.servlet.http.HttpServletRequest;

/**
 * Created on 2024-10-18
 */
public class UserHolderHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return CurrentUserHolder.class.isAssignableFrom(parameter.getParameterType());
    }


    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
            NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest nativeRequest = (HttpServletRequest) webRequest.getNativeRequest();

        CurrentUserHolder userHolder = (CurrentUserHolder) nativeRequest.getAttribute(CurrentUserHolder.HOLDER_KEY);
        if (userHolder == null) {
            // 未登录状态
            userHolder = new CurrentUserHolder();
        }
        return userHolder;
    }


}
